"""
通过线程来处理接受到的数据
测试性能: (10000 个请求，并发500)
time ab -n 10000 -c 500 http://127.0.0.1:4444/
"""
import socket
import threading

import time

import sys


def simpleserver(port):
    s = socket.socket()
    s.bind(('0.0.0.0', port))
    s.listen(2500)
    while True:
        cli, addr = s.accept()
        print(str(addr))
        t = threading.Thread(target=handle_request, args=(cli, time.sleep))
        t.daemon = True
        t.start()


def handle_request(s, sleep):
    try:
        s.recv(1024)
        sleep(0.5)
        s.send('''http/1.0 200 OK
                  Hello World! ''')
        s.shutdown(socket.SHUT_WR)
        print('.', end='')

    except Exception as ex:
        print(ex)
    finally:
        sys.stdout.flush()
        s.close()

if __name__ == '__main__':
    simpleserver(4444)